#!/bin/sh

ls index.md >/dev/null \
|| { 
  echo "Looks I am not in a post directory." 1>&2
  exit 1
}

p_slug=$(head index.md \
| grep -E "^url: " \
| cut -c 6-)
# TODO? assert url ends with a /
p_date="$(date +%FT%T%z | sed 's/\(..\)$/:\1/')"
export p_slug p_date

p_title=$(head index.md \
| grep -E "^title: " \
| cut -c 8-)
export p_title
ls comments.xml > /dev/null 2>&1 || {
  echo "creating comments.xml" 1>&2
  envsubst < "${0}.comments.tpl" > comments.xml
}

echo "adding comment" 1>&2
read -rp "Author:  " c_author
read -rp "Content: " c_content

tmp="tmp-$$"
{
  c_num="$(xmllint -xpath "count(/*/*[local-name()='entry'])" comments.xml)"
  export c_num c_author c_content
  # remove the line </feed>
  #head -n $(( $(wc -l comments.xml | awk '{print $1}') - 1 )) comments.xml
  grep -v '</feed>' comments.xml
  envsubst < "${0}.entry.tpl"
  echo '</feed>'
} \
| xmllint \
  --encode utf-8 \
  --format \
  --output "${tmp}" \
  - \
&& mv "${tmp}" comments.xml

"${EDITOR}" comments.xml

xmllint --relaxng ../../../tools/atom.rng --noout comments.xml
